<template>
  <div class="brand-products">
    <el-container>
      <el-main>
        <!-- 页面标题 -->
        <div class="page-header">
          <h1 class="page-title">
            {{ brandName || '品牌商品' }}
          </h1>
          <p class="page-subtitle">发现更多优质商品</p>
        </div>

        <!-- 筛选和排序 -->
        <div class="filter-section">
          <!-- 筛选选项 -->
          <div class="filter-options">
            <el-button
              v-for="filter in filters"
              :key="filter.value"
              :type="selectedFilter === filter.value ? 'primary' : 'default'"
              @click="selectFilter(filter.value)"
              size="small"
            >
              {{ filter.label }}
            </el-button>
          </div>

          <!-- 排序选项 -->
          <div class="sort-options">
            <span class="sort-label">排序：</span>
            <el-select v-model="sortBy" @change="handleSort" size="small" style="width: 150px">
              <el-option label="默认排序" value="default" />
              <el-option label="价格从低到高" value="price-asc" />
              <el-option label="价格从高到低" value="price-desc" />
              <el-option label="销量优先" value="sales" />
              <el-option label="最新上架" value="newest" />
            </el-select>
          </div>
        </div>

        <!-- 商品列表 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <div v-else-if="products.length === 0" class="empty-container">
          <el-empty description="该品牌下暂时没有商品，请稍后再来看看" />
        </div>

        <div v-else class="products-grid">
          <ProductCard
            v-for="product in products"
            :key="getProductId(product)"
            :product="product"
            @click="goToProduct(getProductId(product))"
          />
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProductList } from '@/api/productService'
import ProductCard from '@/components/ProductCard.vue'
import type { Product } from '@/types/product'

const route = useRoute()
const router = useRouter()

// 响应式数据
const products = ref<Product[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const brandName = ref('')
const selectedFilter = ref('all')
const sortBy = ref('default')

// 筛选选项
const filters = [
  { label: '全部', value: 'all' },
  { label: '新品', value: 'new' },
  { label: '热销', value: 'hot' },
  { label: '促销', value: 'sale' },
]

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 方法
const fetchProducts = async () => {
  if (!route.params.id) return

  loading.value = true
  try {
    const brandId = Number(route.params.id)
    const response = await getProductList({
      brandId,
      page: currentPage.value,
      pageSize: pageSize.value,
      filter: selectedFilter.value === 'all' ? undefined : selectedFilter.value,
      sortBy: sortBy.value,
    })

    products.value = response.data.data.list || []
    total.value = response.data.data.total || 0
    brandName.value = (route.params.brandName as string) || '品牌商品'
  } catch (error) {
    console.error('获取品牌商品失败:', error)
    products.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const selectFilter = (filter: string) => {
  selectedFilter.value = filter
  currentPage.value = 1
  fetchProducts()
}

const handleSort = () => {
  currentPage.value = 1
  fetchProducts()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchProducts()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchProducts()
}

const goToProduct = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 获取商品ID的辅助函数，兼容不同的数据结构
const getProductId = (product: any) => {
  return product.shoeId || product.id || product.productId
}

// 监听路由参数变化
watch(
  () => route.params.id,
  () => {
    currentPage.value = 1
    fetchProducts()
  },
)

// 组件挂载时获取数据
onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.brand-products {
  min-height: calc(100vh - 64px);
  background-color: #f8fafc;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 16px;
  color: #909399;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-label {
  font-size: 14px;
  color: #606266;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .filter-section {
    padding: 16px;
  }

  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
}
</style>
